//FYI: https://github.com/Tencent/puerts/blob/master/doc/unity/manual.md

import { FairyEditor , FairyGUI, System} from 'csharp';
import { $typeof } from 'puerts';
const App = FairyEditor.App;
const Path = System.IO.Path;
const CUR_PATH = eval("__dirname");
const Path_Project = CUR_PATH.substr(0, CUR_PATH.indexOf("/"));
const Path_Bin = Path_Project + "\\bin\\";
const ROOT_BIN = FairyEditor.App.pluginManager.basePath + "\\" + Path_Bin;
const FAIRUI = ROOT_BIN + "res\\";
const CACHE_FILEPATH = ROOT_BIN + ".cache";


// console.log("--------->FAIRUI: " +  FAIRUI);

let cacheMap = loadCache();

function onEnable()
{
    // console.log("main onEnable");
}

function onDestroy() 
{
    // console.log("main onDestroy");
}

function saveCache()
{
    // 
    if( !System.IO.File.Exists(CACHE_FILEPATH) )
    {
        let dir = Path.GetDirectoryName(CACHE_FILEPATH);
        if(!System.IO.Directory.Exists(dir))
        {
            System.IO.Directory.CreateDirectory(dir);
        }
        let file:any = System.IO.File.Create( CACHE_FILEPATH ); 
        file.Close();
        console.log("创建文件: " + CACHE_FILEPATH);                              
    }
    
    let json = JSON.stringify( cacheMap );
    try {
        System.IO.File.WriteAllText( CACHE_FILEPATH , json , System.Text.Encoding.UTF8); 
        //console.log("------>写入文件成功 url: " + CACHE_FILEPATH + " json: " + json);
    } catch (error) {
        console.log("------>写入文件失败 url: " + CACHE_FILEPATH + " json: " + json);  
        console.error( error );
    }
}

function loadCache():object
{
    if( System.IO.File.Exists(CACHE_FILEPATH) )
    {
        try {
            let txt = System.IO.File.ReadAllText( CACHE_FILEPATH ) || "{}"; 
            let obj = JSON.parse(txt);
            //console.log("------>读取cache成功: " + CACHE_FILEPATH + " json: " + txt + " psdPath: "+obj["psdFile"]);
            return obj;
        } catch (error) {
            console.log("读取缓存失败");  
            console.error( error );
        }                         
    }
    return {};
}

function browsePsdFile(view:FairyGUI.GComponent)
{
    // console.log("打开本地目录",System.IO.Directory.GetCurrentDirectory());
    let psdPath = cacheMap["psdFile"] ? Path.GetDirectoryName(cacheMap["psdFile"]) : App.project.basePath;
    FairyEditor.IOUtil.BrowseForOpen("选择要解析的psd文件", psdPath,null,(file) => {
        if(!file.endsWith("psd"))
        {
            App.Alert("请选择psd文件");
            return;
        }
        file && ((view['input_psd'] as FairyGUI.GTextInput).text = file);
        cacheMap["psdFile"] = file;
        saveCache();
    });
}

function converPsd(view:FairyGUI.GComponent)
{
    let psdFilePath =  (view['input_psd'] as FairyGUI.GTextInput).text || "";
    let packName = (view['input_package'] as FairyGUI.GTextInput).text || "";
    let comName = (view['input_com'] as FairyGUI.GTextInput).text || "";
    
    if(!psdFilePath.endsWith("psd"))
    {
        App.Alert("请选择psd文件");
        return;
    }

    if(!System.IO.File.Exists(psdFilePath))
    {
        App.Alert(`不存在改文件${psdFilePath}`);
        return;
    }

    if(!packName)
    {
        App.Alert("请输入组件的所在的包");
        return;
    }

    if(!comName)
    {
        App.Alert("请输入组件的名称");
        return;
    }
    startConvertPsd2Fgui(view,psdFilePath,packName,comName);
}

function touchCallback(view:FairyGUI.GComponent, betnName:string)
{
    if(betnName == 'btn_close')
    {         
        closePsd2FguiDialog(view);
    }
    else if(betnName == 'btn_browse')
    {
        browsePsdFile(view);
    }
    else if(betnName == 'btn_ok')
    {
        converPsd(view);
    }
}

function createPsd2FguiDialog():FairyGUI.GComponent
{
    let panel = FairyGUI.UIPackage.CreateObject("psd2fgui" , "main" ).asCom;
    let view = new FairyGUI.GComponent();
    view.x = Math.ceil((1980 - panel.viewWidth) * 0.5);
    view.y = Math.ceil((1080 - panel.viewHeight) * 0.5);
    view.AddChild(panel);
    view.draggable = true;
    FairyGUI.GRoot.inst.AddChild(view);

    //bind btnCallback and obj
    for (let i: number = 0; i < panel.numChildren; i++) 
    { 
        let disObj = panel.GetChildAt(i);
        view[disObj.name] = disObj;
        if (disObj instanceof FairyGUI.GButton) 
        {
            disObj.onClick.Add((context:FairyGUI.EventContext)=>{
                let sender = context.sender as FairyGUI.GButton;
                let btnName = sender ? sender.name: "";
                touchCallback(view,btnName);
            });
        }
    }

    if(cacheMap["psdFile"])
    {
        (view['input_psd'] as FairyGUI.GTextInput).text = cacheMap["psdFile"];
    }
    return view;
}

function closePsd2FguiDialog(view:FairyGUI.GComponent):void
{
    for (let i: number = 0; i < view.numChildren; i++) 
    { 
        let disObj = view.GetChildAt(i);
        if (disObj instanceof FairyGUI.GButton) 
        {
            disObj.onClick.Clear();
        }
    }
    view.RemoveFromParent();
}

function startConvertPsd2Fgui(view:FairyGUI.GComponent,psdFilePath:string,packName:string,comName:string)
{
    let txtMsg = (view['txt_msg'] as FairyGUI.GTextField);
    txtMsg.text = "转换中...";
    let arr: System.Array = System.Array.CreateInstance($typeof(System.String), 4) ;
    arr.SetValue(psdFilePath,0);
    let outPath = App.project.assetsPath;
    arr.SetValue(outPath,1);
    arr.SetValue(packName,2);
    arr.SetValue(comName,3);
    let batPath = ROOT_BIN+"psd2fgui.bat";
    console.log("----:",batPath,psdFilePath,outPath,packName,comName)
    setTimeout(()=>{
        let exeStr = FairyEditor.ProcessUtil.Start(batPath,arr as System.Array$1<string>,ROOT_BIN,true);
        //console.log("exeStr:",+exeStr);
        txtMsg.text = "";
        let packname = packName;
        App.Alert(exeStr ? "转换失败" : "转换完成",null,()=>{
            App.RefreshProject();
            let fPack:FairyEditor.FPackage = App.project.GetPackageByName(packname);
            let fPackItem = fPack.FindItemByName(comName);
            App.libView.OpenResource(fPackItem);
            App.libView.Highlight(fPackItem,true);
            closePsd2FguiDialog(view);
        });
    },20);
}

App.add_onProjectOpened( ()=>{
    // console.log("main add_onProjectOpened");
    let menu = FairyEditor.App.menu.GetSubMenu( "tool" );
    menu && menu.AddSeperator();//添加分割
    menu && menu.AddItem( "加载psd" , "" , ()=>{
        createPsd2FguiDialog();
    });
});

FairyEditor.App.pluginManager.LoadUIPackage(FAIRUI + 'psd2fgui');
export { onEnable, onDestroy }; 